//    Copyright (C) 2013  <lugocreation@gmail.com>
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>
package org.jpgolay.wi.salesperson;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.*;
import org.jpgolay.gui.fixed.BasicMenu;
import org.jpgolay.gui.iconBar.*;
import org.jpgolay.wi.persistence.ObjectCRUD;
import org.jpgolay.wi.util.BrowserControl;
import org.jpgolay.wi.util.Parameter;

// Referenced classes of package org.jpgolay.wi.salesperson:
//            SalesPersonGUI, SalesPerson
public class SalesPersonController extends SalesPersonGUI {

    public SalesPersonController(Parameter param) {
        create = false;
        updateRowsTable = true;
        write = false;
        this.param = param;
        crud = new ObjectCRUD();
        initLaw();
        initMenu();
        initIconBar();
        initField();
        initSalesPersonList();
    }

    private void initLaw() {
        write = true;
    }

    private void initMenu() {
        getMenuPanel().getExit().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionExit();
            }
        });
        getMenuPanel().getDelete().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionRemove();
            }
        });
        getMenuPanel().getHelp().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionHelp();
            }
        });
        getMenuPanel().getModify().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionModify();
            }
        });
        getMenuPanel().getNew().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionNew();
            }
        });
        getMenuPanel().getOpen().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent actionevent) {
            }
        });
        getMenuPanel().getPrint().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionPrint(true);
            }
        });
        getMenuPanel().getSave().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionSave();
            }
        });
    }

    private void initIconBar() {
        getIconBarPanel().addAnswerListener(new AnswerListener() {
            public void create(AnswerEvent e) {
                actionNew();
            }

            public void open(AnswerEvent answerevent) {
            }

            public void modify(AnswerEvent e) {
                actionModify();
            }

            public void save(AnswerEvent e) {
                actionSave();
            }

            public void remove(AnswerEvent e) {
                actionRemove();
            }

            public void print(AnswerEvent e) {
                actionPrint(false);
            }

            public void help(AnswerEvent e) {
                actionHelp();
            }
        });
    }

    private void initField() {
        cleanField();
        setEnabledField(false);
        getIconBarPanel().setEnabledCreate(write);
        getIconBarPanel().setEnabledSave(false);
        getIconBarPanel().setEnabledModify(false);
        getIconBarPanel().setEnabledRemove(false);
        getIconBarPanel().setEnabledPrint(false);
        getIconBarPanel().setEnabledOpen(false);
        getMenuPanel().getNew().setEnabled(write);
        getMenuPanel().getSave().setEnabled(false);
        getMenuPanel().getModify().setEnabled(false);
        getMenuPanel().getDelete().setEnabled(false);
        getMenuPanel().getPrint().setEnabled(false);
        getMenuPanel().getOpen().setEnabled(false);
        create = false;
    }

    private void initSalesPersonList() {
        java.util.Collection c = crud.readAll(null, 9);
        if (c != null) {
            SalesPerson salesPerson = null;
            salesPersonList = new ArrayList(c);
            Iterator it = salesPersonList.iterator();
            String list[] = new String[salesPersonList.size()];
            for (int i = 0; it.hasNext(); i++) {
                salesPerson = (SalesPerson) it.next();
                list[i] = salesPerson.getFirstname() + " " + salesPerson.getLastname();
            }

            setSalesPersonList(list);
            getSalesPersonComboBox().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    actionLoad(getSalesPersonComboBox().getSelectedIndex());
                }
            });
        } else {
            setSalesPersonList(new String[]{
                        "aucun"
                    });
        }
    }

    private void actionExit() {
        setVisible(false);
    }

    private void actionRemove() {
        int reponse = JOptionPane.showConfirmDialog(null, "\nEtes-vous certain de vouloir suprimer ce Commercial ?", "Confirmation", 1, 2, null);
        switch (reponse) {
            case 0: // '\0'
                actionDelete();
            // fall through

            case -1:
            case 1: // '\001'
            case 2: // '\002'
            default:
                return;
        }
    }

    private void actionHelp() {
        BrowserControl.displayURL("www.ifacile.com");
    }

    private void actionModify() {
        setEnabledField(true);
        getIconBarPanel().setEnabledCreate(false);
        getIconBarPanel().setEnabledSave(true);
        getIconBarPanel().setEnabledModify(false);
        getIconBarPanel().setEnabledRemove(true);
        getMenuPanel().getNew().setEnabled(false);
        getMenuPanel().getSave().setEnabled(true);
        getMenuPanel().getModify().setEnabled(false);
        getMenuPanel().getDelete().setEnabled(true);
    }

    private void actionNew() {
        initField();
        setEnabledField(true);
        getIconBarPanel().setEnabledCreate(false);
        getIconBarPanel().setEnabledSave(true);
        getMenuPanel().getNew().setEnabled(false);
        getMenuPanel().getSave().setEnabled(true);
        create = true;
    }

    private void actionPrint(boolean flag) {
    }

    private void actionSave() {
        if (create) {
            actionCreate();
        } else {
            actionUpdate();
        }
    }

    private void actionLoad(int index) {
        SalesPerson salesPerson = (SalesPerson) salesPersonList.get(index);
        initField();
        setLastUpdate(salesPerson.getLastTime());
        setLastUser(salesPerson.getLastUserId());
        setFirstname(salesPerson.getFirstname());
        setLastname(salesPerson.getLastname());
        setAddrLn1(salesPerson.getAddrLn1());
        setAddrLn2(salesPerson.getAddrLn2());
        setZip(salesPerson.getZip());
        setCity(salesPerson.getCity());
        setCountry(salesPerson.getCountry());
        setTel(salesPerson.getTel());
        setCel(salesPerson.getCel());
        setFax(salesPerson.getFax());
        setEmail(salesPerson.getEmail());
        setFamily(salesPerson.getSalesPersonFamily());
        setSector(salesPerson.getArea());
        setLevel(salesPerson.getLevel());
        if (salesPerson.getObjectif() != null) {
            setGoal(salesPerson.getObjectif().toString());
        }
        if (salesPerson.getResults() != null) {
            setResult(salesPerson.getResults().toString());
        }
        setGoalDate(salesPerson.getObjectifDate());
        setResultDate(salesPerson.getResultsDate());
        if (salesPerson.getSalesRate() != null) {
            setRate1(salesPerson.getSalesRate().toString());
        }
        if (salesPerson.getTotalSalesRate() != null) {
            setRate2(salesPerson.getTotalSalesRate().toString());
        }
        setNotes(salesPerson.getNotes());
        setTitle("COMMERCIAL (CODE : " + salesPerson.getId() + ")");
        getIconBarPanel().setEnabledModify(write);
        getIconBarPanel().setEnabledPrint(true);
        getMenuPanel().getModify().setEnabled(write);
        getMenuPanel().getPrint().setEnabled(true);
        create = false;
    }

    private void actionUpdate() {
        if (verifyRequirement()) {
            SalesPerson salesPerson = (SalesPerson) salesPersonList.get(getSalesPersonComboBox().getSelectedIndex());
            salesPerson.setLastUserId(param.getUserId().toString());
            salesPerson.setFirstname(getFirstname());
            salesPerson.setLastname(getLastname());
            salesPerson.setAddrLn1(getAddrLn1());
            salesPerson.setAddrLn2(getAddrLn2());
            salesPerson.setZip(getZip());
            salesPerson.setCity(getCity());
            salesPerson.setCountry(getCountry());
            salesPerson.setTel(getTel());
            salesPerson.setCel(getCel());
            salesPerson.setFax(getFax());
            salesPerson.setEmail(getEmail());
            salesPerson.setSalesPersonFamily(getFamily());
            salesPerson.setArea(getSector());
            salesPerson.setLevel(getLevel());
            salesPerson.setObjectif(new BigDecimal(getGoal()));
            salesPerson.setResults(new BigDecimal(getResult()));
            salesPerson.setObjectifDate(getGoalDate());
            salesPerson.setResultsDate(getResultDate());
            salesPerson.setSalesRate(new BigDecimal(getRate1()));
            salesPerson.setTotalSalesRate(new BigDecimal(getRate2()));
            salesPerson.setNotes(getNotes());
            crud.update(salesPerson, 9);
            initField();
            initSalesPersonList();
        }
    }

    private void actionCreate() {
        if (verifyRequirement()) {
            Integer pk = crud.create(9);
            if (pk != null) {
                SalesPerson salesPerson = (SalesPerson) crud.read(pk, 9);
                if (salesPerson != null) {
                    salesPerson.setLastUserId(param.getUserId().toString());
                    salesPerson.setFirstname(getFirstname());
                    salesPerson.setLastname(getLastname());
                    salesPerson.setAddrLn1(getAddrLn1());
                    salesPerson.setAddrLn2(getAddrLn2());
                    salesPerson.setZip(getZip());
                    salesPerson.setCity(getCity());
                    salesPerson.setCountry(getCountry());
                    salesPerson.setTel(getTel());
                    salesPerson.setCel(getCel());
                    salesPerson.setFax(getFax());
                    salesPerson.setEmail(getEmail());
                    salesPerson.setSalesPersonFamily(getFamily());
                    salesPerson.setArea(getSector());
                    salesPerson.setLevel(getLevel());
                    salesPerson.setObjectif(new BigDecimal(getGoal()));
                    salesPerson.setResults(new BigDecimal(getResult()));
                    salesPerson.setObjectifDate(getGoalDate());
                    salesPerson.setResultsDate(getResultDate());
                    salesPerson.setSalesRate(new BigDecimal(getRate1()));
                    salesPerson.setTotalSalesRate(new BigDecimal(getRate2()));
                    salesPerson.setNotes(getNotes());
                    crud.update(salesPerson, 9);
                    initField();
                    initSalesPersonList();
                }
            } else {
                JOptionPane.showMessageDialog(null, "Cr\351ation refus\351e !");
            }
        }
    }

    private void actionDelete() {
        SalesPerson salesPerson = (SalesPerson) salesPersonList.get(getSalesPersonComboBox().getSelectedIndex());
        crud.delete(salesPerson.getId(), salesPerson.getLastTime(), 9);
        initField();
        initSalesPersonList();
    }

    private boolean verifyRequirement() {
        if (getFirstname() != null && getFirstname().length() > 50) {
            JOptionPane.showMessageDialog(null, "Pr\351nom trop long (maxi. 50 caract\350res) !");
            return false;
        }
        if (getLastname() != null && getLastname().length() > 50) {
            JOptionPane.showMessageDialog(null, "Nom trop long (maxi. 50 caract\350res) !");
            return false;
        }
        if (getAddrLn1() != null && getAddrLn1().length() > 100) {
            JOptionPane.showMessageDialog(null, "Adresse ligne 1 trop longue (maxi. 100 caract\350res) !");
            return false;
        }
        if (getAddrLn2() != null && getAddrLn2().length() > 100) {
            JOptionPane.showMessageDialog(null, "Adresse ligne 2 trop longue (maxi. 100 caract\350res) !");
            return false;
        }
        if (getZip() != null && getZip().length() > 20) {
            JOptionPane.showMessageDialog(null, "Code postal trop long (maxi. 20 caract\350res) !");
            return false;
        }
        if (getCity() != null && getCity().length() > 50) {
            JOptionPane.showMessageDialog(null, "Ville trop longue (maxi. 50 caract\350res) !");
            return false;
        }
        if (getCountry() != null && getCountry().length() > 50) {
            JOptionPane.showMessageDialog(null, "Pays trop long (maxi. 50 caract\350res) !");
            return false;
        }
        if (getTel() != null && getTel().length() > 20) {
            JOptionPane.showMessageDialog(null, "T\351l trop long (maxi. 20 caract\350res) !");
            return false;
        }
        if (getFax() != null && getFax().length() > 20) {
            JOptionPane.showMessageDialog(null, "Fax trop long (maxi. 20 caract\350res) !");
            return false;
        }
        if (getCel() != null && getCel().length() > 20) {
            JOptionPane.showMessageDialog(null, "Portable trop long (maxi. 20 caract\350res) !");
            return false;
        }
        if (getEmail() != null && getEmail().length() > 100) {
            JOptionPane.showMessageDialog(null, "Email trop long (maxi. 100 caract\350res) !");
            return false;
        }
        if (getSector() != null && getSector().length() > 50) {
            JOptionPane.showMessageDialog(null, "Secteur trop long (maxi. 50 caract\350res) !");
            return false;
        }
        if (getLevel() != null && getLevel().length() > 50) {
            JOptionPane.showMessageDialog(null, "Niveau trop long (maxi. 50 caract\350res) !");
            return false;
        }
        if (getNotes() != null && getNotes().length() > 250) {
            JOptionPane.showMessageDialog(null, "Commentaire trop long (maxi. 250 caract\350res) !");
            return false;
        }
        try {
            new BigDecimal(getGoal());
        } catch (NumberFormatException nfe) {
            setGoal("0.00");
            JOptionPane.showMessageDialog(null, "Objectif refus\351 (nombre d\351cimal uniquement) !");
        }
        try {
            new BigDecimal(getResult());
        } catch (NumberFormatException nfe) {
            setResult("0.00");
            JOptionPane.showMessageDialog(null, "R\351sultat refus\351 (nombre d\351cimal uniquement) !");
        }
        try {
            new BigDecimal(getRate1());
        } catch (NumberFormatException nfe) {
            setRate1("0.00");
            JOptionPane.showMessageDialog(null, "Taux 1 refus\351 (nombre d\351cimal uniquement) !");
        }
        try {
            new BigDecimal(getRate2());
        } catch (NumberFormatException nfe) {
            setRate2("0.00");
            JOptionPane.showMessageDialog(null, "Taux 2 refus\351 (nombre d\351cimal uniquement) !");
        }
        return true;
    }
    private ObjectCRUD crud;
    private Parameter param;
    private ArrayList salesPersonList;
    private boolean create;
    private boolean updateRowsTable;
    private boolean write;
}
